﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OpenMVCRM.ViewModels;
using OpenMVCRM.DataAccess;
using OpenMVCRM.Services;
using OpenMVCRM.Entities;
namespace OpenMVCRM.Controllers
{
    public class ClientsController : BaseController
    {
        private IRepositary repo;
        public ClientsController()
        {
            repo = new Repositary();
        }
        public ActionResult Index()
        {

            var res = repo.GetClientsForOrganization(GetCurrentOrgID());
            var clientEntities = ClientService.GetClientVMs(res);
            return View(clientEntities);
        }

        public ActionResult Create()
        {
            ClientViewModel objClient = new ClientViewModel();
            objClient.States = new List<State>();
            objClient.Countries = repo.GetCountries();
            objClient.Industries = ClientService.GetIndustries();

            return View(objClient);
        }
        [HttpPost]
        public ActionResult Create(ClientViewModel model)
        {

            if (ModelState.IsValid)
            {
                int currentOrgId = GetCurrentOrgID();

                Client clientEntity = new Client();
                clientEntity.Name = model.Name;
                clientEntity.Description = model.Description;
                clientEntity.CreatedDate = DateTime.Now;
                clientEntity.ModifiedDate = clientEntity.CreatedDate;
                clientEntity.WebSite = model.WebSite;
                clientEntity.IndustryID = model.SelectedIndustryId;
                clientEntity.CreatedBy.ID = GetCurrentUserID();
                clientEntity.OrganizationID = currentOrgId;

                var clientResult = repo.SaveClient(clientEntity);
                if (clientResult.Status)
                {
                    if (!String.IsNullOrEmpty(model.PrimaryPhone.Number))
                    {
                        clientEntity.ID = clientResult.OperationID;
                        var phone = new PhoneNumber() { Number = model.PrimaryPhone.Number, OwnerID = clientEntity.ID, Type = "Home", IsPrimary = true };
                        var phoneResult = repo.SavePhoneNumber(phone);
                    }


                    if ((!String.IsNullOrEmpty(model.AddressLine1)) || (!String.IsNullOrEmpty(model.AddressLine2)))
                    {
                        clientEntity.Address = new Address();
                        clientEntity.Address.AddressLine1 = model.AddressLine1;
                        clientEntity.Address.AddressLine2 = model.AddressLine2;
                        clientEntity.Address.City = model.City;
                        clientEntity.Address.StateID = model.SelectedStateID ?? 0;
                        clientEntity.Address.CountryID = model.SelectedCountryID ?? 0;
                        clientEntity.Address.OwnerID = clientEntity.ID;
                        var addressResult = repo.SaveAddress(clientEntity.Address);

                    }
                    return RedirectToAction("View", new { @id = clientEntity.ID, @m = "c" });
                }
                else
                {
                    ModelState.AddModelError("", clientResult.Message);
                }

            }
            model.Industries = ClientService.GetIndustries();
            return View(model);
        }

        public ActionResult View(int id, string m = null)
        {
            Client client = repo.GetClientById(id);
            ClientViewModel objClient = new ClientViewModel();

            objClient = ClientService.GetClientVM(client);
            // objClient.Addresses = ClientService.GetAddressVMs(repo.GetAddresses(id)).OrderByDescending(x => x.ID).ToList();

            if (!String.IsNullOrEmpty(m))
            {
                if (m == "c")
                    objClient.Message = "Created Successfully";
                else if (m == "u")
                    objClient.Message = "Updated Successfully";
            }

            return View(objClient);
        }

        public ActionResult EditAddress(int id, int clientId)
        {
            var objClient = new AddClientAddressViewModel();

            var address = repo.GetAddress(id);
            objClient.AddressId = id;
            objClient.AddressLine1 = address.AddressLine1;
            objClient.AddressLine2 = address.AddressLine2;
            objClient.City = address.City;
            objClient.ZipCode = address.ZipCode;
            objClient.ClientId = clientId;
            objClient.Countries = repo.GetCountries();
            objClient.States = repo.GetStates(address.CountryID);
            objClient.SelectedStateID = address.StateID;
            objClient.SelectedCountryID = address.CountryID;
            //  objClient.IsPrimary = address.IsPrimary;
            // objClient.ClientName = ClientService.GetClientVM(address.Client).Name;
            objClient.AddressId = id;
            return View(objClient);

        }

        [HttpPost]
        public ActionResult EditAddress(AddClientAddressViewModel model)
        {

            if (ModelState.IsValid)
            {
                Address address = repo.GetAddress(model.AddressId);
                address.AddressID = model.AddressId;
                address.AddressLine1 = model.AddressLine1;
                address.AddressLine2 = model.AddressLine2;
                address.City = model.City;
                address.ZipCode = model.ZipCode;
                address.AddressID = model.AddressId;
                //  address.ClientID = model.ClientId;
                // address.IsPrimary = model.IsPrimary;
                address.StateID = model.SelectedStateID;
                address.CountryID = model.SelectedCountryID;
                var result = repo.SaveAddress(address);
                if (result.Status)
                    return RedirectToAction("AddressAdded", new { @id = model.ClientId, @m = "u" });

            }
            else
            {
                var errors = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToArray();
                if (errors != null)
                {

                }
            }


            model.ClientName = ClientService.GetClientVM(repo.GetClientById(model.ClientId)).Name;
            return View(model);
        }



        [HttpPost]
        public ActionResult AddAddress(AddClientAddressViewModel model)
        {

            if (ModelState.IsValid)
            {
                Address address = new Address();
                address.AddressLine1 = model.AddressLine1;
                address.AddressLine2 = model.AddressLine2;
                address.City = model.City;
                address.ZipCode = model.ZipCode;
                // address.ClientID = model.ClientId;
                // address.IsPrimary = model.IsPrimary;
                address.CountryID = model.SelectedCountryID;
                address.StateID = model.SelectedStateID;
                var result = repo.SaveAddress(address);
                if (result.Status)
                    return RedirectToAction("AddressAdded", new { @id = model.ClientId, @m = "c" });

            }

            model.ClientName = ClientService.GetClientVM(repo.GetClientById(model.ClientId)).Name;
            model.Countries = repo.GetCountries();
            model.States = new List<State>();
            return View(model);
        }

        [HttpPost]
        public string Test(string coord)
        {
            return "1 : " + coord;
        }

        public ActionResult AddressAdded(int id, string m)
        {



            var client = ClientService.GetClientVM(repo.GetClientById(id));
            // client.Addresses = ClientService.GetAddressVMs(repo.GetAddresses(id)).OrderByDescending(x=>x.ID).ToList();

            if (m == "c")
                client.Message = "Address Created Successfully";
            else if (m == "u")
                client.Message = "Address Updated Successfully";
            return View(client);
        }

        public ActionResult DeleteAddress(int id)
        {
            var client = ClientService.GetClientVM(repo.GetClientById(id));
            var vm = new DeleteClientAddressViewModel();
            vm.Client = client;
            var addressEntity = repo.GetAddress(id);
            if (addressEntity != null)
            {
                vm.AddressToDelete = ClientService.GetAddressVM(addressEntity);
                //    vm.Client.ID = addressEntity.ClientID;
            }

            return View(vm);
        }
        [HttpPost]
        public ActionResult DeleteAddress(DeleteClientAddressViewModel model)
        {

            var res = repo.DeleteAddress(model.AddressToDelete.ID);
            if (res.Status)
                return RedirectToAction("View", new { @id = model.Client.ID, @m = "d" });

            return View(model);
        }

        //public ActionResult View(int id)
        //{

        //}

        public ActionResult Edit(int id)
        {
            var objClient = new ClientViewModel();
            var client = repo.GetClientById(id);
            objClient = ClientService.GetClientVM(client);
            objClient.Industries = ClientService.GetIndustries();
            objClient.Countries = repo.GetCountries();
            objClient.SelectedIndustryId = client.Industry.ID;




            return View(objClient);
        }
        [HttpPost]
        public ActionResult Edit(ClientViewModel model)
        {
            if (ModelState.IsValid)
            {
                Client clientEntity = new Client { ID = model.ID };
                clientEntity.Name = model.Name;
                clientEntity.Description = model.Description;
                clientEntity.WebSite = model.WebSite;
                clientEntity.IndustryID = model.SelectedIndustryId;
                var result = repo.SaveClient(clientEntity);

                //if ((!String.IsNullOrEmpty(model.AddressLine1)) || (!String.IsNullOrEmpty(model.AddressLine2)))
                //{
                //    clientEntity.Address = new Address();
                //    clientEntity.Address.AddressLine1 = model.AddressLine1;
                //    clientEntity.Address.AddressLine2 = model.AddressLine2;
                //    clientEntity.Address.City = model.City;
                //    clientEntity.Address.StateID = model.SelectedStateID ?? 0;
                //    clientEntity.Address.CountryID = model.SelectedCountryID ?? 0;
                //}

                //var res=repo.UpdateClient(clientEntity);
                if (result.Status)
                    return RedirectToAction("View", new { @id = result.OperationID, @m = "u" });

                else
                    ModelState.AddModelError("", result.Message);

            }
            model.Industries = ClientService.GetIndustries();
            return View(model);
        }


        [HttpPost]
        public ActionResult Delete(int ID, string btn)
        {

            var result = repo.DeleteClient(ID);
            if (result.Status)
            {
                if (Request.IsAjaxRequest())
                    return Json(new { Status = true });
                else
                    return RedirectToAction("Index");
            }
            return RedirectToAction("Index");

        }

        //[HttpPost]
        //public ActionResult Edit(ClientViewModel model)
        //{
        //    if (ModelState.IsValid)
        //    {



        //    }
        //    return View(model);
        //}


        //public ActionResult Delete(int id)
        //{

        //}
        //[HttpPost]
        //public ActionResult Delete(int id)
        //{

        //}

    }
}
